<template>
  <div class="upload-excel-component">
    <el-button type="primary" @click="dialogVisible = true">
      导入人员数据
    </el-button>
    <el-dialog
      v-model="dialogVisible"
      title="导入数据"
      width="520px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form ref="formRef" :model="form" :rules="rules">
        <el-form-item prop="file" label="导入人员数据" label-width="110px">
          <el-upload
            ref="uploadRef"
            v-model:file-list="form.file"
            class="upload-excel"
            drag
            :auto-upload="false"
            :show-file-list="true"
            :accept="'.xlsx,.xls'"
            :limit="1"
            :on-success="handleSuccess"
            :on-change="handleChange"
            :on-exceed="handleExceed"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <template #tip>
              <div class="el-upload__tip">
                请上传Excel文件，仅支持xlsx、xls格式
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item prop="batchNo" label="批次号" label-width="110px">
          <el-input
            v-model="form.batchNo"
            class="number-input"
            placeholder="请输入批次号，如：20250201-1"
            maxlength="16"
            @input="handleInput"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelUpload">取消</el-button>
          <el-button type="primary" @click="confirmUpload">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, defineProps, computed, defineEmits } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import { infoApi } from '@/api/modules'
import { UploadFilled } from '@element-plus/icons-vue'

const props = defineProps({
  url: {
    type: String,
    default: '',
  },
})
const emit = defineEmits(['update:modelValue'])

const uploadRef = ref(null)
const formRef = ref(null)
const dialogVisible = ref(false)

const currentDate = computed(() => {
  const today = new Date()
  const year = today.getFullYear()
  const month = String(today.getMonth() + 1).padStart(2, '0')
  const day = String(today.getDate()).padStart(2, '0')
  return `${year}${month}${day}`
})

const form = reactive({
  batchNo: '',
  file: [],
})

const rules = {
  batchNo: [
    { required: true, message: '请输入批次号', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入批次号'))
        } else if (!/^\d{8}-\d{1,8}$/.test(value)) {
          callback(new Error('批次号格式错误，正确格式为：YYYYMMDD-NNNNN'))
        } else {
          const dateStr = value.split('-')[0]
          const date = new Date(
            dateStr.slice(0, 4) +
              '-' +
              dateStr.slice(4, 6) +
              '-' +
              dateStr.slice(6, 8)
          )
          if (date.toString() === 'Invalid Date' || date.getFullYear() < 2000) {
            callback(new Error('请输入有效的日期'))
          } else {
            callback()
          }
        }
      },
      trigger: 'blur',
    },
  ],
  file: [
    { required: true, message: '请上传Excel文件', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (!value || value.length === 0) {
          callback(new Error('请上传Excel文件'))
        } else {
          callback()
        }
      },
      trigger: 'change',
    },
  ],
}

const handleChange = (file) => {
  formRef.value.validateField('file', (valid, value) => {
    if (value?.file?.length === 1) {
      formRef.value.clearValidate('file')
    }
  })
}

const handleExceed = (files) => {
  uploadRef.value.clearFiles()
  const file = files[0]
  uploadRef.value.handleStart(file)
}

const confirmUpload = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      const loading = ElLoading.service({
        lock: true,
        text: '正在导入数据...',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      const formData = new FormData()
      formData.append('file', form.file[0].raw)
      formData.append('batchNo', form.batchNo)
      dialogVisible.value = false

      try {
        const response = await infoApi.excelExport.post(formData)
        if (response.code === 200) {
          ElMessage.success('导入成功')
          form.batchNo = ''
          dialogVisible.value = false
        } else {
          ElMessage.error(response.message || '导入失败')
        }
      } catch (error) {
        ElMessage.error(error.error || '导入失败')
      } finally {
        loading.close()
        emit('upload-end')
      }
    }
  })
}

const cancelUpload = () => {
  dialogVisible.value = false
  formRef.value.resetFields()
  form.batchNo = ''
}

const handleInput = (value) => {
  // 先移除非法字符
  let newValue = value.replace(/[^\d-]/g, '')

  // 如果有多个连字符，只保留第一个
  const firstHyphenIndex = newValue.indexOf('-')
  if (firstHyphenIndex !== -1) {
    const beforeHyphen = newValue.slice(0, firstHyphenIndex)
    const afterHyphen = newValue.slice(firstHyphenIndex + 1).replace(/-/g, '')
    newValue = beforeHyphen + '-' + afterHyphen
  }

  // 限制日期部分为8位
  const parts = newValue.split('-')
  if (parts[0] && parts[0].length > 8) {
    parts[0] = parts[0].slice(0, 8)
  }

  // 限制序号部分为7位
  if (parts[1] && parts[1].length > 7) {
    parts[1] = parts[1].slice(0, 7)
  }

  form.batchNo = parts.join('-')
}
</script>

<style lang="scss" scoped>
.upload-excel-component {
  .upload-excel {
    width: 100%;
  }

  :deep(.el-upload__tip) {
    color: #909399;
    font-size: 12px;
    margin-top: 8px;
  }

  .icon {
    margin-right: 4px;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }
}
</style>
